<template>
  <el-main>
    <div id="teamiob" class="container-xl my-home-div"
      :style="{ minHeight: '60vh', '--bs-gutter-x': 0, '--my-home-div-height': '56px' }">
      <div class="my-home-div-line row">
        <div class="col">

          <span>
            <svg class="icon" aria-hidden="true">
              <use xlink:href="#icon-a-icon_team_TaskListSquare"></use>
            </svg>
            团队任务列表
          </span>

        </div>
        <div class="col top-0 text-right">
          <router-link v-if="team.ID" v-slot="{ navigate }" custom :to="{
            name: '创建工作',
            params: { ID: team?.ID },
          }">
            <el-button size="default" type="primary" @click="navigate">+ &nbsp;
              创建任务
            </el-button>
          </router-link>
        </div>
      </div>
      <div v-if="countnum" class="row row1" :style="{ borderBottom: '1px solid var(--color--117)' }">
        <div class="col">
          任务名
        </div>
        <div :style="{ width: '120px' }" class="text-center">
          任务类型
        </div>
        <div :style="{ width: '120px' }" class="text-center">
          开始时间
        </div>
        <div :style="{ width: '120px' }" class="text-center">
          结束时间
        </div>
        <div :style="{ width: '120px' }" class="text-center">
          任务状态
        </div>
        <div :style="{ width: '120px' }" class="text-center">
          完成人数
        </div>
        <div :style="{ width: '270px' }" class="text-center">
          操作
        </div>
        <div :style="{ width: '40px' }" class="text-center"></div>
      </div>
      <div v-if="countnum" :style="{ paddingLeft: '24px', paddingRight: '24px' }">
        <teamjoblistVue v-for="row in tabledata" :row="row" :user="store.state.user" :data="p.team" :start="start"
          :isAdmin="1" :click="chakanclick" :del="del" :_tabledata="_tabledata(row.type)">
        </teamjoblistVue>
      </div>
      <div class="row row1" v-if="countnum">
        <div class="col text-right">
          <el-pagination :page-size="limit" :total="countnum" hide-on-single-page @current-change="change"
            layout="prev, pager, next" :current-page="Math.floor(offset / limit) + 1"></el-pagination>
        </div>
      </div>
      <el-empty v-if="!countnum" image="https://cdn.hterobot.com/JOY/oj_1_1/Not%20Found%20illustration.png" />
      <el-dialog v-model="dialogVisible" :title="job ? job.name : '没有找到'" width="700px">
        <template #header>
          <div class="container-fluid" :style="{
            backgroundColor: 'var(--color-43)',
            color: '#fff',
            margin: '-20px',
            width: '700px',
            padding: '24px'
          }">
            <div class="row">
              <div class="col" :style="{ fontSize: '18px' }">
                {{ job ? job.name : '没有找到' }}
              </div>
            </div>
            <div class="row">
              <div class="col-8">
                <div>
                  类型： {{ job.type !== 'question' ? '观看视频' : '题目练习' }}
                </div>
                <div v-if="job.ID">
                  任务状态: {{ times(job) }}
                </div>
              </div>
              <div class="col-4 text-right">
                <el-button @click="download" size="default" type="primary">导出</el-button>
              </div>
            </div>

          </div>
        </template>
        <div class="container-fluid">
          <div class="row row-fluid">
            <div class="col">成员</div>
            <div class="col text-center">完成进度</div>
            <div class="col text-center">完成时间</div>
          </div>
          <div v-for="(v, i) in jobuser" class="row cu"
            :style="{ height: '48px', lineHeight: '48px', marginTop: '6px', backgroundColor: '#fafafa' }"
            @click="getuserquestion(v.teamjobrelation.map(e => e.userquestionid), Number(v.userid))">
            <div class="col ">
              {{ v.user?.name }}
            </div>
            <div class="col text-center">
              {{ v.wcd }}%
            </div>
            <div class="col text-center">
              {{ v.times ? TimeYH1(v.times) : '-' }}
            </div>
          </div>
        </div>
        <el-dialog v-model="dialogVisible2" :title="name" width="700px">
          <el-table :data="userquestion" v-loading="userquestionloading" border style="width: 100%">
            <el-table-column prop="questionid" width="100" label="题号">
              <template #default="scope">
                <div :title="scope.row.question.name" class="questionname">
                  <router-link v-slot="{ href }" custom :to="{
                    name: '题目',
                    params: { ID: scope.row.questionid },
                  }">
                    <el-link target="_blank" :href="href">{{
                      scope.row.questionid
                    }}
                    </el-link>
                  </router-link>
                </div>
              </template>
            </el-table-column>
            <el-table-column prop="question.name" width="250" label="题目名称">
              <template #default="scope">
                <div :title="scope.row.question.name" class="questionname">
                  <router-link v-slot="{ href }" custom :to="{
                    name: '题目',
                    params: { ID: scope.row.questionid },
                  }">
                    <el-link target="_blank" :href="href">{{
                      scope.row.question.name
                    }}
                    </el-link>
                  </router-link>
                </div>
              </template>
            </el-table-column>
            <el-table-column width="100" label="提交答案">
              <template #default="scope">
                <span class="cu" v-show="scope.row.type == '代码'" @click="download2(scope.row)">
                  查看源码</span>
              </template>
            </el-table-column>
            <el-table-column prop="resultdataarr" label="编程题测试点">
            </el-table-column>
          </el-table>
        </el-dialog>
        <el-dialog v-model="dialogVisible3" :title="name" width="700px">
          <el-table :data="watchvideo" v-loading="userquestionloading" border style="width: 100%">
            <el-table-column prop="questionid" width="100" label="课程编号">
              <template #default="scope">
                <div :title="scope.row.name" class="questionname">
                  <el-link target="_blank"
                    :href="`https://www.hterobot.com/home.html#/course/${scope.row.courseid}?lession=0&catebag=${scope.row.catebagid}`">{{
                      scope.row.courseid
                    }}
                  </el-link>
                </div>
              </template>
            </el-table-column>
            <el-table-column prop="question" width="250" label="课程名称">
              <template #default="scope">
                <div :title="scope.row.name" class="questionname">

                  <el-link target="_blank"
                    :href="`https://www.hterobot.com/home.html#/course/${scope.row.courseid}?lession=0&catebag=${scope.row.catebagid}`">{{
                      scope.row.name
                    }}
                  </el-link>
                </div>
              </template>
            </el-table-column>
            <el-table-column prop="time" label="已观看时间">

            </el-table-column>
          </el-table>
        </el-dialog>
        <el-dialog v-model="dialogVisible4" :title="name" width="700px">
          <el-table :data="teamfile" v-loading="userquestionloading" border style="width: 100%">
            <el-table-column prop="teamfileid" width="100" label="文件编号">
            </el-table-column>
            <el-table-column prop="name" width="250" label="文件名称">
            </el-table-column>
            <el-table-column prop="state" width="250" label="是否下载">
              <template #default="scope">
                {{ scope.row.state ? '已下载' : '未下载' }}
              </template>
            </el-table-column>
          </el-table>
        </el-dialog>
      </el-dialog>
    </div>
  </el-main>
</template>

<script setup lang="ts">
import { ElMessage, ElMessageBox } from 'element-plus';
import { computed, onMounted, ref, watch } from 'vue';
import { useRoute } from 'vue-router';
import { asyncselectuserquestion, asyncteamdelteamjob, asyncteamselectteamjob } from '../../../api';
import Studycodemodel from '../../../mysql_interface/studycodemodel';
import { TimeYH1 } from '../../../util/time'
import teamjoblistVue from './teamjoblist.vue';
import { getExceltodownload } from '../../../util/excel';
import { download2 } from '../../../util/code';
import dayjs from 'dayjs'
import Alymodel from '../../../mysql_interface/model';
import { useStore } from 'vuex';
import { Storekey } from '../../../interface';
const dialogVisible = ref(false)
const dialogVisible2 = ref(false)
const dialogVisible3 = ref(false)
const dialogVisible4 = ref(false)
const id = ref<number>()
const p = defineProps<{
  team: Studycodemodel.Iteam,
  ID: number
}>()

const tabledata = ref<Studycodemodel.Iteamjob[]>([])
const countnum = ref(0)
const store = useStore(Storekey)
const route = useRoute()
const questions = ref<Studycodemodel.Iquestion[]>([])
const courses = ref<Alymodel.IMcourse[]>([])
const teamfiles = ref<Studycodemodel.Iteamfile[]>([])

const offset = ref(0)
const limit = ref(20)
const n = ref([])

function _tabledata(v?: string) {
  if (v === 'video') {
    return courses.value
  }
  if (v === 'question') {
    return questions.value
  }
  if (v === 'file') {
    return teamfiles.value
  }
  return []
}

onMounted(() => {
  start()
})

const job = computed(() => {
  return tabledata.value.find(e => e.ID === id.value) || {}
})


const teamusers = ref<Studycodemodel.Iteamuser[]>([])

function times(data: Studycodemodel.Iteamjob) {
  const { starttime, endtime } = data
  const n = Date.now()
  if (n < new Date(starttime || new Date).getTime()) {
    return '未开始'
  }
  if (n > new Date(endtime || new Date).getTime()) {
    return '已结束'
  }
  return '进行中'
}



async function start() {
  const { rows, count, question, course, teamfile } = await asyncteamselectteamjob({
    _offset: offset.value,
    _limit: limit.value,
    teamid: p.ID,
    _order: 'ID'
  })
  questions.value = question.map(e => { return { ID: e.ID, name: e.name } })
  courses.value = course.map(e => { return { ID: e.ID, name: e.name } })
  teamfiles.value = teamfile.map(e => { return { ID: e.ID, name: e.name } })
  tabledata.value = rows
  countnum.value = count
}



function change(r: number) {
  offset.value = (r - 1) * limit.value
}

function del(ID?: number) {
  ElMessageBox.confirm("确定要删除该任务？", "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  }).then(() => {
    asyncteamdelteamjob({ ID, teamid: p.team?.ID }).then(() => {
      ElMessage.success('删除成功')
      start()
    }).catch(() => {
      ElMessage.info('删除失败')
    })
  })
}


const userquestion = ref<Studycodemodel.Iuserquestion[]>([])


const userid = ref(0)


const watchvideo = computed(() => {
  return tabledata.value.find(e => e.ID === id.value)?.teamjobrelation?.filter(t => t.userid === userid.value).map(f => {
    const { courseid, watchvideoid, catebagid, state } = f
    const course = courses.value.find(t => t.ID === courseid)
    return {
      courseid,
      name: course?.name,
      time: watchvideoid?.map(f => f.time).reduce((a = 0, b = 0) => a + b, 0) || 0,
      catebagid,
      state
    }
  }) || []
})

const teamfile = computed(() => {
  return tabledata.value.find(e => e.ID === id.value)?.teamjobrelation?.filter(t => t.userid === userid.value).map(f => {
    const { teamfileid, state } = f
    const course = teamfiles.value.find(t => t.ID === teamfileid)
    return {
      teamfileid,
      name: course?.name,
      state
    }
  }) || []
})

const userquestionloading = ref(false)

const name = ref<string>()

async function getuserquestion(ID: (number | undefined)[], _userid: number) {
  const job = tabledata.value.find(t => t.ID === id.value)
  const user = teamusers.value.find(e => e.userid === _userid)
  name.value = user?.user?.name
  if (job?.type === 'question') {
    dialogVisible2.value = true
    userquestionloading.value = true
    userquestion.value = []
    await asyncselectuserquestion({ ID }).then(e => {
      userquestion.value = e.rows
      userquestionloading.value = false

    }).catch(f => {
      console.log(f)
      userquestionloading.value = false

    })
  } else if (job?.type === 'video') {
    dialogVisible3.value = true
    userid.value = _userid
  } else if (job?.type === 'file') {
    dialogVisible4.value = true
    userid.value = _userid
  }
}


function download() {
  const data = [['成员', '完成进度', '完成时间']]
  for (let v of jobuser.value.filter(e => e.wcd)) {
    console.log(v)
    const n = [v.user?.name || '', v.wcd + '%', v.times ? new Date(v.times).toLocaleString() : '']
    data.push(n)
  }
  getExceltodownload(data, String(job.value.name))
}




function chakanclick(ID?: number) {
  if (ID) {
    id.value = ID
    dialogVisible.value = true
  }
}

const jobuser = computed(() => {
  const questionnum = job.value.questionnum || 1
  const relation = job.value?.teamjobrelation || []
  const usersid = relation.map(e => e.userid)
  const users = teamusers.value.filter(a => usersid.includes(a.userid)) || []
  return users.map(a => {
    const t = relation.filter(z => z.state === true && z.userid === a.userid)
    const _wcd = Math.floor(t.length / questionnum * 100)
    const wcd = _wcd > 100 ? 100 : _wcd
    let times: number | undefined = 0
    if (wcd === 100) {
      for (let v of t) {
        const z = dayjs(v.updatedAt).unix() * 1000
        if (!times) {
          times = z
        } else if (times < z) {
          times = z
        }
      }
    }
    return {
      ...a,
      wcd: wcd > 100 ? 100 : wcd,
      times,
      teamjobrelation: t
    }
  }).sort((a, b) => new Date(b.times).getTime() - new Date(a.times).getTime()).sort((a, b) => b.wcd - a.wcd)
})

watch(() => offset.value, () => {
  start()
})

</script>

<style scoped>
.head1 {
  background: #f6f6f6;
  height: 90px;
  line-height: 90px;
  border-radius: 8px 8px 0px 0px;
  position: relative;
  text-align: center;
}

.button-p {
  position: absolute;
  right: 24px;
  top: 24px;
}

#teamiob .mytable {
  width: 100%;
  --el-table-header-text-color: var(--color-43);
  --el-table-tr-bg-color: var(--color-43);
  --el-table-text-color: #fff;
}

.row {
  transition: all 0.3s;
}

.row1 {
  color: var(--color-22);
  font-weight: 700;
  line-height: 48px;
  margin-bottom: 12px;
  --bs-gutter-x: 0;
  padding-left: 12px;
  padding-right: 12px;
}

.cu:hover {
  color: var(--color-cheng);
}

.row-fluid {
  border-bottom: 1px solid #434343;
  height: 48px;
  color: var(--color-43);
  line-height: 48px;
  font-weight: 700
}
</style>
